import { getASCIICount, isASCII } from './utils'

// 文本分行
export default function getTspans (text, num, enFontScale) {
  const tspans = []
  let start = 0
  const paragraphs = getParagraphs(text)
  paragraphs.forEach(p => {
    const rows = getRows(p, num, start, enFontScale)
    tspans.push(...rows)
    start = start + p.length + 1
  })
  // 最后一段落的最后一行如果不为空行要减去换行符
  const last = tspans.length - 1
  if (tspans[last].type !== 'empty') {
    tspans[last].end -= 1
  // 最后一段落如果为空段落则倒数第一、二行都要减去换行符
  } else {
    tspans[last - 1] && (tspans[last - 1].end -= 1)
    tspans[last].start -= 1
    tspans[last].end -= 1
  }
  return tspans
}

// 根据换行符将 text 分割为多段
function getParagraphs (text) {
  return text.split(/\u000A/i)
}

// 将段落分割为多行
function getRows (text, num, start, enFontScale) {
  // 空段落特别处理
  if (text === '') {
    return [{
      type: 'empty',
      text: '',
      start: start,
      end: start
    }]
  }
  let rows = []
  let rowStart = start
  while (text.length > num) {
    const rowText = getRowText(text, '', num, enFontScale)
    rows.push({
      type: 'normal',
      text: rowText,
      start: rowStart,
      end: rowStart + rowText.length - 1
    })
    rowStart += rowText.length
    text = text.slice(rowText.length)
  }
  if (text) {
    rows.push({
      type: 'normal',
      text,
      start: rowStart,
      end: rowStart + text.length - 1
    })
  }
  // 段落最后一行必须加上换行字符
  rows[rows.length - 1].end += 1
  return rows
}

// 获取指定数量宽度下能容纳的最长字符串
function getRowText (text, preText, num, enFontScale) {
  if (num === 0) return ''
  const length = preText.length
  if (num < 1) {
    const char = text.slice(length, length + 1)
    return isASCII(char) ? char : ''
  }
  const rowNum = Math.floor(num)
  const rowText = text.slice(length, length + rowNum)
  const asc = (getASCIICount(rowText) * (1 - enFontScale)) + (num - rowNum)
  return rowText + getRowText(text, preText + rowText, asc, enFontScale)
}